package com.example.memorypoint.mvp.date;

import android.util.Log;

import com.example.memorypoint.DateBase.DiaryDatabase;
import com.example.memorypoint.entity.Diary;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class DatePresenterImpl implements DateContract.DataPresenter {

    private DateContract.DataView view;
    private DiaryDatabase diaryDatabase;

    public DatePresenterImpl(DateContract.DataView view, DiaryDatabase diaryDatabase) {
        this.view = view;
        this.diaryDatabase = diaryDatabase;
    }

    @Override
    public void loadData(String date) {
        // 如果 date 为 null，则使用今天的日期（格式：yyyy-MM-dd）
        if (date == null) {
            LocalDate today = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            date = today.format(formatter);
        }
        try {
            List<Diary> diaries = diaryDatabase.getDiariesByDate(date);
            // 计算日记数量
            String diaryCount = String.valueOf(diaries.size());
            // 计算字词数量：统计每篇日记标题和内容的字符长度之和
            int count = 0;
            for (Diary diary : diaries) {
                count += (diary.getTitle().length() + diary.getContent().length());
                Log.e("ppp", "bt  "+diary.getTitle().length());
                Log.e("ppp", "zhengwen  "+diary.getContent().length());

            }
            String wordCount = String.valueOf(count);
            view.showData(diaryCount, wordCount);
        } catch (Exception e) {
            view.showError("加载数据失败：" + e.getMessage());
        }
    }

    @Override
    public void detachView() {
        view = null;
    }
}
